package hello.app;

import hello.app.model.HelloApi;
import hello.app.model.HelloSetting;
import hello.app.model.ModelManager;
import hello.app.util.AdteToast;
import hello.app.util.Util;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

/**
 * 設定画面
 * @author taketo
 *
 */
public class SettingActivity extends PreferenceActivity implements OnPreferenceChangeListener {

	private static final int DIALOG_UNKOWN_ERROR = 0;
	private static final int DIALOG_DISEBALE_NETWORK = 1;

	private static final int MENU_ID_FEEDBACK = (Menu.FIRST + 1);
	private static final int MENU_ID_BACK = (Menu.FIRST + 2);

	protected ModelManager mManger;
	protected HelloSetting mSetting;
	protected HelloApi mApi;


	public static void start(Context context){
		Intent in = new Intent(context,SettingActivity.class);
		in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(in);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.pref);
		mManger = ModelManager.getInstatce(this);
		mSetting = mManger.getHelloSetting();
		mApi = mManger.getHelloApi();
		initEventListener();
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // メニューアイテムを追加します
        menu.add(Menu.NONE, MENU_ID_FEEDBACK, Menu.NONE, getString(R.string.setting_menu_feedback));
        menu.add(Menu.NONE, MENU_ID_BACK, Menu.NONE, getString(R.string.setting_menu_back));
        return super.onCreateOptionsMenu(menu);
    }

	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        boolean ret = true;
        switch (item.getItemId()) {
        case MENU_ID_FEEDBACK:
        	Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:dev.suzuki@gmail.com"));
        	intent.putExtra(Intent.EXTRA_SUBJECT, "誰着?エラー報告及び改善要望");
        	intent.putExtra(Intent.EXTRA_TEXT, "誰着?エラー報告及び改善要望をお知らせ下さい\n\n--------------以下入力欄--------------");
        	startActivity(intent);
        	break;
        case MENU_ID_BACK:
        	finish();
        	break;
        default:
            ret = super.onOptionsItemSelected(item);
            break;
        }
		return ret;
	}

	/**
	 * イベントの初期化
	 */
	private void initEventListener(){
		String[] cbpIdArray = new String[]{
				getString(R.string.hello_enabled),
				getString(R.string.display_pos_selector),
				getString(R.string.history_display_count_edit)
		};
		for(String id : cbpIdArray){
			Preference pref = (Preference) findPreference(id);
			pref.setOnPreferenceChangeListener(this);
		}
	}


	public boolean onPreferenceChange(Preference preference, Object newValue) {
		if(isEqualKey(preference, getString(R.string.hello_enabled))){
			Boolean enable = (Boolean)newValue;
			if(enable){
				startService(new Intent(this, PhoneService.class));
			}else{
				stopService(new Intent(this, PhoneService.class));
			}
		}else if(isEqualKey(preference, getString(R.string.display_pos_selector))){

			int displayPos = isEqualKey(preference,getString(R.string.display_pos_selector)) ? Integer.valueOf((String)newValue) : mSetting.getDisplayPostion();

			String msg = String.format("~サンプル表示~\n%s:0 %s:0",getString(R.string.good),getString(R.string.bad));
			AdteToast adteToast = AdteToast.getInstance(getBaseContext());
			adteToast.show(msg, displayPos, 3500);

		}else if(isEqualKey(preference, getString(R.string.history_display_count_edit))){
			String numberStr = (String)newValue;
			if(Util.isIntString(numberStr)){
				int number = Integer.valueOf(numberStr);
				if(number <= 0){
					Toast.makeText(this, "1件以上は設定が有効です", Toast.LENGTH_SHORT).show();
					return false;
				}
				if(number > HelloSetting.MAX_HISTORY_DISPLAY_COUNT){
					Toast.makeText(this, "最大表示件数を超えています", Toast.LENGTH_SHORT).show();
					return false;
				}
			}else{
				Toast.makeText(this, "数値のみを入力して下さい", Toast.LENGTH_SHORT).show();
				return false;
			}
		}
		return true;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DISEBALE_NETWORK:
			return createDialog(Application.TITLE, "ネットワークエラーです");
		case DIALOG_UNKOWN_ERROR:
			return createDialog(Application.TITLE, "エラーが起きました");
		default:
			return super.onCreateDialog(id);
		}
	}

	protected Dialog createDialog(String title, String message) {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title).setIcon(android.R.drawable.stat_sys_warning)
				.setMessage(message).setCancelable(false)
				.setPositiveButton(android.R.string.ok, null);
		return builder.create();
	}

	protected boolean isEqualKey(Preference preference, String key){
		return preference.getKey().equals(key);
	}



}
